<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
// to-do: sales -> juris -> distributor selection
function stock_info_add_page($id) {
    return drupal_get_form('stock_info_edit_form', $id);
}

function stock_info_edit_page($id) {
    return drupal_get_form('stock_info_edit_form', $id);
}

function stock_info_clone_page($id) {
    return drupal_get_form('stock_info_edit_form', $id);
}

function stock_info_edit_form($form, &$form_state) {
    if (!empty($_GET['distributor_id'])) {
        $form_state['distributor_id'] = $_GET['distributor_id'];
    }
    if(empty( $form_state['distributor_id'])) {}else{
        $form['#distributor_id'] = $form_state['distributor_id'];
        $res = get_info($form['#distributor_id'],'distributor');
        $form['#distributor_name'] = $res[0]->distributor_name;
//        $addr_red = get_all_addrname($res[0]->addr_id);
//        $province = $addr_red[0]->province?$addr_red[0]->province:"";
//        $city = $addr_red[0]->city? '  '.$addr_red[0]->city:"";
//        $county = $addr_red[0]->county? '  '.$addr_red[0]->county:"";
//        $town = $addr_red[0]->town? '  '.$addr_red[0]->town:"";
//        $village = $addr_red[0]->village? '  '.$addr_red[0]->village:"";
//        $form['#farmer_addr'] =$province.$city.$county.$town.$village;
    }
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('stock_info', 'stock_info_id', $id);
        if (empty($record)) {
            drupal_set_message(t('库存信息不存在！'), 'status', FALSE);
            return $form;
        }
    }
    // 判断用户角色
    if(!nonghua_user_access('stock_info', 'view', $id, !empty($record) ? $record->author_uid:0, !empty($record) ? $record->distributor_id:0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    $form['stock_info_author'] = array(
//        '#type' => 'fieldset',
//        '#title' => '上报人',
//        '#collapsed' => false,
//        '#collapsible' => true,
    );
    global $user;
    @$user_info = _get_user_info($record->author_uid);
    $form['stock_info_author']['author'] = array(
        '#type' => 'textfield',
        '#title' => '上报人',
        '#size' => 32,
        '#maxlength' => 32,
        '#default_value' => $user_info['name'],
        '#disabled' => TRUE,
    );
    if(!empty($_GET['distributor_id'])){
        $record->distributor_id = $_GET['distributor_id'];
    }
//    $form['stock_info_distributor']['distributor'] = _insert_login_salesman_distributor_selection_form($form,$form_state,$user->uid,!empty($record) ? $record->distributor_id:'');
    $form['distributor_name'] = _insert_distributor_select_info($form,$form_state,$record->distributor_id);
    for ($i = 0; $i < variable_get("stock_info_years_total", 5); $i++) {
        $year_options[date('Y')-$i] = date('Y')-$i;
    }
    if(empty($record)){
        $year_default = date('Y');
    }else{
        $year_default = $record->year;
    }

    $form['stock_info_date']['year'] = array(
        '#title' =>  '年度',
        '#type' => 'select',
        '#validated' => TRUE,
        '#required' => TRUE,
        '#options' => $year_options,
        '#default_value' => $year_default,
    );

    for ($i = 1; $i <= 12; $i++) {
        $month_options[$i] = $i;
    }
    if(empty($record)){
        $month_default = date('n');
    }else{
        $month_default = $record->month;
    }
    $form['stock_info_date']['month'] = array(
        '#title' =>  '月份',
        '#type' => 'select',
        '#validated' => TRUE,
        '#required' => TRUE,
        '#options' => $month_options,
        '#default_value' => $month_default,
    );

    $form['stock_info_sacf']['sacfvariety'] = _insert_sacfvariety_selection_form(!empty($record) ? $record->sacfvariety_id:'','选择撒可富化肥品种');

    $form['stock_info_amount']['last_month_stock'] = array(
        '#type' => 'textfield',
        '#title' => '上月库存（吨）',
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->last_month_stock:'',
    );

    $form['stock_info_amount']['return_stock'] = array(
        '#type' => 'textfield',
        '#title' => '退库数量（吨）',
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->return_stock:'',
    );

    $form['stock_info_amount']['this_month_instock'] = array(
        '#type' => 'textfield',
        '#title' => '本月入库（吨）',
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->this_month_instock:'',
    );
    $form['stock_info_amount']['this_month_outstock'] = array(
        '#type' => 'textfield',
        '#title' => '本月出库（吨）',
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->this_month_outstock:'',
    );
    $form['stock_info_amount']['this_month_stock'] = array(
        '#type' => 'textfield',
        '#title' => '本月库存（吨）',
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->this_month_stock:'',
    );
    $form['stock_info_amount']['this_month_sales'] = array(
        '#type' => 'textfield',
        '#title' => '本月销量（吨）',
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->this_month_sales:'',
    );
    $form['stock_info_amount']['details'] = array(
        '#type' => 'textarea',
        '#title' => '详细',
        '#size' => 32,
        '#cols' => 1,
        '#maxlength'=>50,
        '#default_value' => !empty($record) ? $record->details:'',
    );
    if(arg(1) == 'add'){
        $button_value = '添加';
    }else{
        if(arg(1) == 'clone'){
            $button_value = '克隆';
        }else{
            $button_value = '修改';
        }
    }
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => $button_value,
        '#access' => nonghua_user_access('stock_info', 'edit', $id, !empty($record) ? $record->author_uid:0,!empty($record) ? $record->distributor_id:'') ,
    );
    return $form;
}

function stock_info_edit_form_validate($form, &$form_state)
{
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : 0;
    if (empty($form_state['values']['author'])) {
        form_set_error('author', '必须填写 上传者');
    }
    if (empty($form_state['values']['distributor_name'])) {
        form_set_error('distributor', '必须填写 经销商');
    }
    if (empty($form_state['values']['year'])) {
        form_set_error('year', '必须填写 年');
    }
    if (empty($form_state['values']['month'])) {
        form_set_error('month', '必须填写 月');
    }
    if (empty($form_state['values']['sacfvariety'])) {
        form_set_error('sacfvariety', '必须填写 撒可富品种');
    }
    if ($form_state['values']['last_month_stock'] == "") {
        form_set_error('last_month_stock', '必须填写 上月库存（吨）');
    }
    if ($form_state['values']['return_stock'] == "") {
        form_set_error('return_stock', '必须填写 退库数量（吨）');
    }
    if ($form_state['values']['this_month_instock'] == "") {
        form_set_error('this_month_instock', '必须填写 本月入库（吨）');
    }
    if ($form_state['values']['this_month_stock'] =="") {
        form_set_error('this_month_stock', '必须填写 本月库存（吨）');
    }
    if ($form_state['values']['this_month_outstock'] == "") {
        form_set_error('this_month_outstock', '必须填写 本月出库（吨）');
    }
    if ($form_state['values']['this_month_sales'] == "") {
        form_set_error('this_month_sales', '必须填写 本月销量（吨）');
    }
    if (!empty($form_state['values']['last_month_stock'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['last_month_stock']) || (strlen(explode('.',$form_state['values']['last_month_stock'])[0])>8)) {
            form_set_error('last_month_stock', "上月库存格式错误");
        }
    }
    if (!empty($form_state['values']['return_stock'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['return_stock']) || (strlen(explode('.',$form_state['values']['return_stock'])[0])>8)) {
            form_set_error('return_stock', "退库数量格式错误");
        }
    }
    if (!empty($form_state['values']['this_month_instock'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['this_month_instock']) || (strlen(explode('.',$form_state['values']['this_month_instock'])[0])>8)) {
            form_set_error('this_month_instock', "本月入库格式错误");
        }
    }
    if (!empty($form_state['values']['this_month_outstock'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['this_month_outstock']) || (strlen(explode('.',$form_state['values']['this_month_outstock'])[0])>8)) {
            form_set_error('this_month_outstock', "本月出库格式错误");
        }
    }
    if (!empty($form_state['values']['this_month_stock'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['this_month_stock']) || (strlen(explode('.',$form_state['values']['this_month_stock'])[0])>8)) {
            form_set_error('this_month_stock', "本月库存格式错误");
        }
    }
    if (!empty($form_state['values']['this_month_sales'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['this_month_sales']) || (strlen(explode('.',$form_state['values']['this_month_sales'])[0])>8)) {
            form_set_error('this_month_sales', "本月销量格式错误");
        }
    }
    if (!empty($form_state['values']['distributor_id']) && !empty($form_state['values']['sacfvariety']) && !empty($form_state['values']['year']) && !empty($form_state['values']['month'])) {
        $query = db_select('stock_info', 's');
        $query->condition('s.stock_info_id', $id);
        $query->condition('s.distributor_id', $form_state['values']['distributor_id']);
        $query->condition('s.sacfvariety_id', $form_state['values']['sacfvariety']);
        $query->condition('s.year', $form_state['values']['year']);
        $query->condition('s.month', $form_state['values']['month']);
        $query->fields('s');
        $record = $query->execute()->fetchObject();
        if (!empty($record)) {
            form_set_error('', "该经销商" . $form_state['values']['year'] . "年" . $form_state['values']['month'] . "月" . "该化肥信息已存在");
        }
    }
    if(!empty($form_state['values']['distributor_name'])){
        $distributor_id = get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false);
        if(empty($distributor_id)){
            form_set_error('distributor_name', "经销商信息不存在！");
        }
    }
}

function stock_info_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (arg(1) == 'add') { //add new stock_info
        try{
            $nid = db_insert('stock_info') // Table name no longer needs {}
            ->fields(array(
                'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
                'sacfvariety_id' => $form_state['values']['sacfvariety'],
                'year' => $form_state['values']['year'],
                'month' => $form_state['values']['month'],
                'last_month_stock' => $form_state['values']['last_month_stock'],
                'return_stock' => $form_state['values']['return_stock'],
                'this_month_instock' => $form_state['values']['this_month_instock'],
                'this_month_outstock' => $form_state['values']['this_month_outstock'],
                'this_month_stock' => $form_state['values']['this_month_stock'],
                'this_month_sales' => $form_state['values']['this_month_sales'],
                'details' => $form_state['values']['details'],
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
            if ($nid > 0) {
                drupal_set_message(t('添加成功！'), 'status', FALSE);
            }
            if(!empty($_GET['distributor_id'])){
                drupal_goto('stock_info/list',array('query' => array('distributor_id' => $_GET['distributor_id'])));
            }
           drupal_goto('stock_info/add/'.$nid);
        }catch (Exception $e){
            watchdog_exception('distributor', $e);
            throw $e;
        }

    } else {
        if(arg(1) == 'clone'){
            $nid = db_insert('stock_info') // Table name no longer needs {}
            ->fields(array(
                'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
                'sacfvariety_id' => $form_state['values']['sacfvariety'],
                'year' => $form_state['values']['year'],
                'month' => $form_state['values']['month'],
                'last_month_stock' => $form_state['values']['last_month_stock'],
                'return_stock' => $form_state['values']['return_stock'],
                'this_month_instock' => $form_state['values']['this_month_instock'],
                'this_month_outstock' => $form_state['values']['this_month_outstock'],
                'this_month_stock' => $form_state['values']['this_month_stock'],
                'this_month_sales' => $form_state['values']['this_month_sales'],
                'details' => $form_state['values']['details'],
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
            if ($nid > 0) {
                drupal_set_message(t('克隆成功！'), 'status', FALSE);
                drupal_goto('stock_info/list');
            }
        }
        $nid = db_update('stock_info') // edit exsting store. todo: update only modified fields
        ->fields(array(
            'distributor_id' => $form_state['values']['distributor_id'],
            'sacfvariety_id' => $form_state['values']['sacfvariety'],
            'year' => $form_state['values']['year'],
            'month' => $form_state['values']['month'],
            'last_month_stock' => $form_state['values']['last_month_stock'],
            'return_stock' => $form_state['values']['return_stock'],
            'this_month_instock' => $form_state['values']['this_month_instock'],
            'this_month_outstock' => $form_state['values']['this_month_outstock'],
            'this_month_stock' => $form_state['values']['this_month_stock'],
            'this_month_sales' => $form_state['values']['this_month_sales'],
            'details' => $form_state['values']['details'],
//            'author_uid' => $user->uid,
            'timestamp' => time(),))
            -> condition('stock_info_id',$id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
        if(!empty($_GET['distributor_id'])){
            drupal_goto('stock_info/list',array('query' => array('distributor_id' => $_GET['distributor_id'])));
        }
    }
}
